﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Linq.Dynamic;
using System.Web.Mvc;
using ChoViet.CMS.ViewModels;
using ChoViet.Lib.Common;
using ChoViet.Lib.Helpers;
using ChoViet.Lib.Paging;
using ChoViet.Model;
using MVCMessage;
using ChoViet.Lib.Mail;
using System.Configuration;
using System.IO;
using ChoViet.CMS.Properties;

namespace ChoViet.CMS.Controllers
{
    [RoleHelper(Roles = RoleSystem.Dictionary)]
    public class EmailSystemController : BaseController
    {
        /// <summary>
        /// Created by: VietLv
        /// Created date: 29/06/2012
        /// Description: Manage tags
        /// </summary>

        ChoVietDataContext eDataContext = new ChoVietDataContext();

        #region GET/Index
        public ActionResult IndexCms(int? page)
        {
            try
            {
                var model = new EmailSystemViewModel();
                if (!page.HasValue) page = 1;
                string order = UserState.getUserStateFromRequest("EmailSystem.order", "order", "ID").ToString();
                string orderDir = UserState.getUserStateFromRequest("EmailSystem.orderDir", "orderDir", "desc").ToString();
                model.Keyword= UserState.getUserStateFromRequest("EmailSystem.Keyword", "Keyword", "").ToString();
                int pageSize = int.Parse(UserState.getUserStateFromRequest("EmailSystem.pageSize", "PageSize", 20).ToString());
                //model.EmailSystems = eDataContext.EmailSystems
                //                        .Where(e=> e.)

                ViewData["orderDir"] = orderDir;
                ViewData["order"] = order;
                return View(model);
            }
            catch (Exception ex)
            {
                ViewData["MessageInfo"] = ex.Message;
                return View();
            }
        }
        #endregion
        #region 
        [HttpPost]
        public ActionResult IndexCms()
        {
            try
            {
                // Gửi mail chuc mừng giáng sinh
                string strSubject = Settings.Default.Email_Subject_MerryChristmas;
                string strBody = Utils.GetTemplateEmail(Settings.Default.Email_Path, Settings.Default.Email_Tempalte_MerryChristmas);
                string fromMail = ConfigurationManager.AppSettings["DefaultFromMail"];
                int maxnumberSend = Request["NumberEmail"] != null ? Convert.ToInt32(Request["NumberEmail"]) : Convert.ToInt32(Settings.Default.Email_MaxNumberSend_Default);
                int customerType = Request["CustomerType"] != null ? Convert.ToInt32(Request["CustomerType"]) : 1;
                string EmailSendError = "";
                if (customerType == 1)
                {
                    var listusers = eDataContext.Users
                                .Select(e => new { e.ID, e.DisplayName, e.Email })
                                .Distinct()
                                .ToList();
                    foreach (var item in listusers)
                    {
                        string subject = string.Format(strSubject, item.DisplayName);
                        string body = string.Format(strBody, "?MemberEmail=" + item.Email);
                        try
                        {
                            SmtpMailer.sendMail(item.Email, fromMail, subject, body);
                        }
                        catch (Exception ex)
                        {
                            EmailSendError += item.Email + ";";
                        }
                    }
                    Messages.AddFlashMessage("Đã gửi email thành công tới :'" + listusers.Count() + "' địa chỉ email");
                    Messages.AddFlashMessage("Danh sách các email gửi bị lỗi:");
                    Messages.AddFlashMessage(EmailSendError);
                }
                else
                {
                    var listEmail = eDataContext.EmailSystems
                        .Where(e => e.IsSendMail == null)
                        .Take(maxnumberSend);

                    foreach (var item in listEmail)
                    {
                        string subject = string.Format(strSubject, string.IsNullOrEmpty(item.FullName) ? item.Email : item.FullName);
                        string body = string.Format(strBody,item.Email);
                        try
                        {
                            SmtpMailer.sendMail(item.Email, fromMail, subject, body);
                            item.IsSendMail = true;
                        }
                        catch (Exception ex)
                        {
                            item.IsSendMail = false;
                           EmailSendError += item.Email + ";";
                        }
                    }
                    eDataContext.SubmitChanges();
                    Messages.AddFlashMessage("Đã gửi email thành công tới :'" + listEmail.Count() + "' địa chỉ email");
                    Messages.AddFlashMessage("Danh sách các email gửi bị lỗi:");
                    Messages.AddFlashMessage(EmailSendError);
                }
            }
            catch (Exception)
            {
                throw;
            }
            return View();
        }
        #endregion

        public ActionResult abss()
        {
            return View(); 
        }

    }
}
